<template>
  <div class="carManager">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i>
          权限管理
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="addVisible = true"
          class="tianjia"
        >添加</el-button>
      </div>
      <el-table
        :data="tableData"
        border
        class="table"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="index" width="55" align="center" label="序号" class-name="table"></el-table-column>
        <el-table-column prop="roleName" label="权限名" width="100" class-name="table"></el-table-column>
        <el-table-column prop="jurList" label="权限列表" width="800" class-name="table"></el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="table">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="cur_page"
          :page-size="pagesize"
          :total="totalRecords"
          :page-sizes="[5, 10, 20, 40]"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </div>
    </div>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <el-form ref="editForm" :model="editForm" label-width="120px">
        <el-form-item label="权限名称">
          <el-input v-model="editForm.name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="权限列表" v-if="upkey">
          <el-checkbox
            :label="item.id"
            name="type"
            v-for="(item,index) in uptype"
            :checked="item.checked"
            :key="index"
            v-model="newuptype"
            style="width:150px"
          >{{item.name}}</el-checkbox>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加弹出框 -->
    <el-dialog title="添加" :visible.sync="addVisible" width="30%">
      <el-form ref="addForm" :model="addForm" label-width="120px">
        <el-form-item label="权限名称">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="权限列表">
          <el-checkbox
            :label="item.id"
            name="type"
            v-for="(item,index) in type"
            :key="index"
            v-model="newtype"
            style="width:150px"
          >{{item.name}}</el-checkbox>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加弹出框 结束-->
    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
      <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteRow">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { fetchData } from '../../api/index';
import Validator from "async-validator";
import { setTimeout } from "timers";
export default {
  name: "carManager",
  data() {
    return {
      upkey: true,
      idlist: [], //获取到的idlist
      newtype: [],
      uptype: [],
      newuptype: [],
      type: [],
      value: "",
      tableData: [],
      cur_page: 1,
      pagesize: 20,
      totalRecords: 0,
      totalPages: 0,
      multipleSelection: [],
      select_cate: "",
      select_word: "",
      del_list: [],
      is_search: false,
      editVisible: false,
      addVisible: false,
      delVisible: false,
      editForm: {
        name: ""
      },
      addForm: {
        name: ""
      },
      idx: -1,
      id: -1
    };
  },
  created() {
    this.getData();
    this.getJur();
  },
  computed: {
    data() {
      return this.tableData.filter(d => {
        let is_del = false;
        for (let i = 0; i < this.del_list.length; i++) {
          if (d.name === this.del_list[i].name) {
            is_del = true;
            break;
          }
        }
        if (!is_del) {
          if (
            d.address.indexOf(this.select_cate) > -1 &&
            (d.name.indexOf(this.select_word) > -1 ||
              d.address.indexOf(this.select_word) > -1)
          ) {
            return d;
          }
        }
      });
    }
  },
  methods: {
    //获取权限选择 【权限】
    getJur() {
      var username = localStorage.ms_username;
      console.log(username)
      var res = this;
      this.$axios({
        url:
          "/api/waterMenu/selectMenuByLoginName/" +username,
        method: "get",
        data: {}
      })
        .then(function(response) {
          if (response.status <= 200) {
            console.log(response.data.data);
            res.type = [];
            res.uptype = [];
            for (var i = 0; i < response.data.data.length; i++) {
              res.type.push({
                id: response.data.data[i].id,
                name:  response.data.data[i].menuName
              });
              res.uptype.push({
                id: response.data.data[i].id,
                name:  response.data.data[i].menuName
              });
            }
            console.log(res.uptype);
          }
        })
        .catch(function(error) {
          res.$message.error("查询失败: " + error);
          console.log(error);
        });
    },
    //每页显示数改变
    handleSizeChange(val) {
      this.pagesize = val;
      this.getData();
    },
    // 分页导航
    handleCurrentChange(val) {
      this.cur_page = val;
      this.getData();
    },
    // 获取 数据
    getData() {
      var username = localStorage.ms_username;
      var res = this;
      res.editVisible = true;
      setTimeout(() => {
        res.editVisible = false;
      }, 20);
      this.$axios({
        url:
          "/api/waterRole/findRoleListByPageAndAgentIdOrStaffId",
        method: "post",
        data: {
          username: username,
          pageNum: res.cur_page,
          pageSize: res.pagesize
        }
      })
        .then(function(response) {
          if (response.status <= 200) {
            res.tableData = response.data.data.list;
            res.totalRecords = response.data.data.total;
            console.log(response.data.data);
            for (var i = 0; i < response.data.data.list.length; i++) {
              res.idlist.push({ id: [] });
              for (
                var j = 0;
                j < response.data.data.list[i].waterMenuList.length;
                j++
              ) {
                res.idlist[i].id.push(
                  response.data.data.list[i].waterMenuList[j].id
                );
              }
            }
            for (var i = 0; i < res.tableData.length; i++) {
              res.tableData[i]["jurList"] = [];
            }
            for (var i = 0; i < res.tableData.length; i++) {
              for (var j = 0; j < res.tableData[i].waterMenuList.length; j++) {
                res.tableData[i].jurList.push(
                  res.tableData[i].waterMenuList[j].menuName + ","
                );
              }
            }
          }
        })
        .catch(function(error) {
         // res.$message.error("查询失败: " + error);
          console.log("查询失败: "  + error);
        });
    },
    formatter(row, column) {
      return row.address;
    },
    filterTag(value, row) {
      return row.tag === value;
    },
    handleEdit(index, row) {
      this.newuptype = [];
      for (var i = 0; i < this.idlist[index].id.length; i++) {
        for (var j = 0; j < this.uptype.length; j++) {
          if (this.idlist[index].id[i] == this.uptype[j].id) {
            this.uptype[j]["checked"] = true;
            this.newuptype.push(this.uptype[j].id);
          }else{
            this.uptype[j]["checked"] = false;
          }
        }
      }
      console.log(this.uptype);
      this.idx = index;
      this.id = row.id;
      this.editForm = {
        id: row.id,
        name: row.roleName
      };
      this.editVisible = true;
    },
    handleDelete(index, row) {
      this.idx = index;
      this.id = row.id;
      this.delVisible = true;
    },
    delAll() {
      const length = this.multipleSelection.length;
      let str = "";
      this.del_list = this.del_list.concat(this.multipleSelection);
      for (let i = 0; i < length; i++) {
        str += this.multipleSelection[i].name + " ";
      }
      this.$message.success("删除了" + str);
      this.multipleSelection = [];
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 保存编辑
    saveEdit() {
      var idList = "";
      for (var i = 0; i < this.newuptype.length; i++) {
        idList = this.newuptype[i] + "," + idList;
      }
      var res = this;
      this.$refs.editForm.validate(valid => {
        if (!valid) {
          res.$message.success("格式不正确");
        } else {
          this.$axios({
            url: "/api/waterRole/updateRoleById",
            method: "put",
            data: {
              id: res.editForm.id,
              menuIdList: idList,
              roleName: res.editForm.name
            }
          })
            .then(function(response) {
              if (response.status <= 200) {
                res.editVisible = false;
                res.$message.success("修改成功");
                res.$message.success(`修改第 ${res.idx + 1} 行成功`);
                console.log("修改成功");
                res.getData();
              }
            })
            .catch(function(error) {
              res.$message.success("修改失败！");
              console.log(error);
            });
        }

        // 验证通过后的处理...
      });
    },
    // 添加
    saveAdd() {
      var idList = "";
      for (var i = 0; i < this.newtype.length; i++) {
        idList = this.newtype[i] + "," + idList;
      }
      var username = localStorage.ms_username;
      var res = this;
      var setData = this.addForm;
      console.log(username, idList, this.addForm.name);
      this.$refs.addForm.validate(valid => {
        if (!valid) {
          res.$message.success("格式不正确");
        } else {
          this.$axios({
            url: "/api/waterRole/addTwo",
            method: "post",
            data: {
              username: username,
              menuIdList: idList,
              roleName: res.addForm.name
            }
          })
            .then(function(response) {
              if (response.status <= 200) {
                res.$message.success(response.data.message);
                res.addVisible = false;
                res.getData();
              }
            })
            .catch(function(error) {
              res.$message.error("添加失败！");
              console.log(error);
            });
        }
      });
    },
    // 确定删除
    deleteRow() {
      var res = this;
      console.log(this.id);
      this.$axios({
        url: "/api/waterRole/deleteRoleById/" + res.id,
        method: "delete",
        data: {}
      })
        .then(function(response) {
          if (response.status <= 200) {
            res.$message.success("删除成功");
            res.delVisible = false;
            res.getData();
          }
        })
        .catch(function(error) {
          res.$message.success("删除失败！");
          console.log(error);
        });
    }
  }
};
</script>

<style scoped>
.huizong {
  height: 30px;
  width: 400px;
  position: relative;
}
.huizong span {
  height: 30px;
  width: 400px;
  position: absolute;
  bottom: -60px;
  z-index: 999;
}
.tianjia {
  margin-left: 10px;
}
.sousuo {
  margin-right: 10px;
}
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.outup {
  font-size: 12px;
  color: #fff;
  background-color: #409eff;
  display: inline-block;
  border-radius: 3px;
  padding: 8px 15px;
  margin-left: 10px;
  margin-top: 3px;
}
.upload-demo {
  height: 30px;
  width: 100px;
  display: inline-block;
  margin-left: 10px;
}
.inup {
  margin-top: 10px;
}
</style>
<style>
.el-upload--text {
  width: 60px;
  height: 30px;
  display: inline-block;
  border: 0;
  overflow: visible;
}
.el-table--border {
  border: 1px solid black;
}
.el-table--border,
.el-table--border th,
.el-table td,
.el-table th {
  border-right: 1px solid black;
  border-bottom-color: black;
  border-left-color: black;
}
.table {
  border-bottom-color: black !important;
  border-left-color: black !important;
}
</style>
